 import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

class InternetAPI {
  static final String GET = "get";
  static final String POST = "post";
  static final String DATA = "datas";
  static final String CODE = "code";
  static final String MSG = "msg";
  static final String FLAG = "flag";

  Dio dio;
  static InternetAPI _instance;

  static InternetAPI getInstance() {
    if (_instance == null) {
      _instance = InternetAPI();
    }
    return _instance;
  }

  InternetAPI() {
    dio = Dio(BaseOptions(
     baseUrl: "http://49.235.45.128:5000/",
//      baseUrl: "http://192.168.1.138:5000/",
      headers: {'platform': 'android'},
      connectTimeout: 5000,
      receiveTimeout: 100000,
      responseType: ResponseType.plain,
    ));
    _addStartHttpInterceptor(dio); //添加请求之前的拦截器
  }

  //get请求
  get(String url, Function successCallBack,
      {params, Function errorCallBack}) async {
    _requstHttp(url, successCallBack, GET, params, errorCallBack);
  }

  //post请求
  post(String url, Function successCallBack,
      {params, Function errorCallBack, Options options}) async {
    _requstHttp(url, successCallBack, POST, params, errorCallBack, options);
  }

  _requstHttp(String url, Function successCallBack,
      [String method, params, Function errorCallBack, Options options]) async {
    String errorMsg = '';
    int code;

    try {
      Response response;
      if (method == GET) {
        if (params != null && params.isNotEmpty) {
          response = await dio.get(url, queryParameters: params);
        } else {
          response = await dio.get(url);
        }
      } else if (method == POST) {
        if (params != null && params.isNotEmpty) {
          if (options != null) {
            response = await dio.post(url, data: params, options: options);
          } else {
            response = await dio.post(url, data: params);
          }
        } else {
          response = await dio.post(url);
        }
      }

      code = response.statusCode;
      if (code != 200){//在这个项目里，后台连接成功返回错误400且有响应体。所以不会出现200并json响应体内判断处理错误消息的情况
        errorMsg = '错误码：' + code.toString() + '，' + response.data;
        _error(errorCallBack, errorMsg);
        return;
      }
      print("返回体中数据" + response.data);
      //String dataStr = json.encode(response.data);
      Map<String, dynamic> dataMap = jsonDecode(response.data);
      if (url.contains("OMSWarehouseInTask/")) {
        //预约单详情接口json数据结构与其他不同，单独处理
        if (dataMap["WarehouseInTask"]["flag"] == "success") {
          successCallBack(dataMap["WarehouseInTask"][DATA]);
        }
      } else if (url.contains("OMSWarehouseOutTask/")) {
        if (dataMap["WarehouseOutTask"]["flag"] == "success") {
          successCallBack(dataMap["WarehouseOutTask"][DATA]);
        }
      } else {
        if (dataMap != null && dataMap[FLAG] != "success") {
          errorMsg = '错误码：' + dataMap[CODE].toString() + '，' + dataMap[MSG];
          _error(errorCallBack, errorMsg);
          print("aaaaaaaaaaaaaa");
          return;
        }
        successCallBack(dataMap[DATA]);
      }
    } catch (exception) {
       print(exception);
       print("嘿嘿");
       if(exception.response!=null){//连接成功报错有返回体会走这里
          if(exception.message.toString().contains("400")){//服务器会在连接成功时有些情况返回400并返回json提示拒绝原因
            Map<String,dynamic> data = jsonDecode(exception.response.toString());
            print("AAA"+exception.response.toString());
            _error(errorCallBack, data["msg"].toString());
          }else{//http404之类错误
            _error(errorCallBack,exception.message.toString());
            print("BBBB"+exception.response.toString());
          }
        }else{//断网连接超时等会走这里
          _error(errorCallBack,exception.message.toString());
        }

    }
  }

  _error(Function errorCallBack, String error) {
    if(error.toString().contains("Connecting timeout[5000ms]")){//自定义提示消息
      Fluttertoast.showToast(
          msg: "网络连接超时",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.blue,
          textColor: Colors.yellow);
    }else if(error.toString().contains("Connection failed")){
      Fluttertoast.showToast(
          msg: "请检查网络",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.blue,
          textColor: Colors.yellow);
    }
    else{
      Fluttertoast.showToast(
          msg: error.toString(),
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.blue,
          textColor: Colors.yellow);
    }
    print(errorCallBack);
    if (errorCallBack != null) {
      errorCallBack(error);
    }
  }

  _addStartHttpInterceptor(Dio dio) {
    dio.interceptors
        .add(InterceptorsWrapper(onRequest: (RequestOptions options) {
          print(options.data);
          print(options.uri);
          print(options.path);
      return options; //continue
      // 如果你想完成请求并返回一些自定义数据，可以返回一个`Response`对象或返回`dio.resolve(data)`。
      // 这样请求将会被终止，上层then会被调用，then中返回的数据将是你的自定义数据data.
      //
      // 如果你想终止请求并触发一个错误,你可以返回一个`DioError`对象，或返回`dio.reject(errMsg)`，
      // 这样请求将被中止并触发异常，上层catchError会被调用。
    }, onResponse: (Response response) {
      // 在返回响应数据之前做一些预处理
      return response; // continue
    }, onError: (DioError e) {
      return e; //continue
    }));
  }
}
